package com.yc.jpa.bean;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;

import lombok.Data;

@Data
public class PageBean {

	private Integer page;
	private Integer size;
	private List<String> order;

	public static PageBean defaultPage() {
		PageBean ret = new PageBean();
		ret.setPage(1);
		ret.setSize(10);
		return ret;
	}

	public Sort getSort() {
		return order == null || order.size() == 0 ? Sort.unsorted() : Sort.by(buildOrders());
	}

	private List<Order> buildOrders() {
		List<Order> ret = new ArrayList<>();
		for (int i = 0; i < order.size(); i++) {
			if (order.get(i).endsWith("!")) {
				ret.add(Order.desc(order.get(i).substring(0, order.get(i).length() - 1)));
			} else {
				ret.add(Order.asc(order.get(i)));
			}
		}
		return ret;
	}

	public Pageable build() {
		if (page == null && size == null) {
			return PageRequest.of(0, Integer.MAX_VALUE, getSort());
		} else {
			page = page == null ? 0 : page - 1;
			size = size == null ? 10 : size;
			return PageRequest.of(page, size, getSort());
		}
	}

}
